<!--
  - Copyright (C) 2024
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
  <view>
    <cu-custom :bgColor="globalData.bgColor" :isBack="false">
      <template #content><text class="text-darkgrey">{{$t('list.index.28pbyw')}}</text></template>
    </cu-custom>
    <view>
      <im-connect></im-connect>
    </view>
    <view class="cu-list menu-avatar">
      <view class="cu-item" :class="modalName=='move-box-'+ index?'move-cur':''"
            v-for="(item,index) in Conversation" :key="index" @touchstart="ListTouchStart"
            @touchmove="ListTouchMove" @touchend="ListTouchEnd" :data-target="'move-box-' + index"
            @click="openChat(item)">
        <view class="cu-avatar round lg" :style="item.faceURL?'background-image:url(' + item.faceURL + ')':''">
          <text class="cuIcon-people" v-if="!item.faceURL"></text>
        </view>
        <!-- <view class="cu-avatar rpinConversationound lg" :style="[{backgroundImage:'url('+item.faceURL+')'}]"></view> -->
        <view class="content">
          <view class="text-grey">
            <text v-if="item.isPinned" class="cuIcon-top text-red text-bold"></text>
            {{ item.showName }}
          </view>
          <view class="text-gray text-sm">{{ item.content }}</view>
        </view>
        <view class="action">
          <view class="text-grey text-xs">{{ formatTimeMsg(item.latestMsgSendTime) }}</view>
          <view v-if="item.unreadCount !=0" class="cu-tag round bg-red sm">{{ item.unreadCount }}</view>
        </view>
        <view class="move">
          <view class="bg-grey" @click.stop="pinConversation(item)">{{ item.isPinned ? $t('list.index.197kqi') : $t('list.index.fhy7hy') }}</view>
          <view class="bg-red" @click.stop="deleteConversation(item)">{{$t('list.index.xj82y7')}}</view>
        </view>
      </view>
    </view>
    <view :class="'cu-load bg-gray ' + (loadmore?'loading':'over')"></view>
  </view>
</template>

<script>
/**
 * Copyright (C) 2024
 * All rights reserved, Designed By www.joolun.com
 * 注意：
 * 本软件为www.joolun.com开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */

import JimUtil from '@/utils/jim-util' // JLIM工具库
import imConnect from '@/components/chat-message/im-connect' //im连接状态
import service from '@/store/service';

export default {
  components: {
    imConnect
  },
  data() {
    return {
      globalData: getApp().globalData,
      IMloginStatus: getApp().globalData.IMdata.IMloginStatus, //状态
      Conversation: null,
      loadmore: false,
      modalName: null,
      listTouchStart: 0,
      listTouchDirection: null,
      userInfo: '',
    };
  },
  watch: {
    IMloginStatus(val) {
    },
  },
  onShow() {
    if (!this.userInfo || !this.userInfo.id) {
      uni.reLaunch({
        url: '/pages/login/index'
      });
      return
    }
    getApp().initJIM().then(res => {
      //刷新会话
      JimUtil.refreshConoversation()
    });
  },
  onLoad(options) {
    this.userInfo = service.getUser()
    // 收到会话更改，更新会话
    uni.$on('JIMConversation', (data) => {
      this.getConversation()
    })
    //连接断开监听
    uni.$on('JIMDisconnect', (data) => {
      this.getConversation();
    })
    //登录监听
    uni.$on('JIMLogin', (data) => {
      this.getConversation();
    })
  },
  onUnload() {
    // uni.off('JIMLogin')
    // uni.off('JIMDisconnect')
    // uni.off('JIMConversation')
  },

  methods: {
    formatTimeMsg(time) {
      return JimUtil.parseTimeMsg(time);
    },
    // 打开聊天
    openChat(item) {
      uni.navigateTo({
        url: '/pages/message/chat/index?chatUserId=' + item.userID + '&showName=' + item.showName
      })
    },
    getConversation() {
      let that = this;
      let JIM = getApp().globalData.JIM;
      this.loadmore = true
      try {
        if (getApp().globalData.IMdata.IMloginStatus) {
          JIM.getAllConversationList().then((res) => {
            if (res.errCode == 0) {
              const data = JSON.parse(res.data);
              this.Conversation = data
              JimUtil.saveConversationList(data)
            }
            that.loadmore = false
          }).catch(err => {
            this.Conversation = JimUtil.getConversationList()
            that.loadmore = false
          });
        } else {
          this.Conversation = JimUtil.getConversationList()
          that.loadmore = false
        }
      } catch (e) {
        this.Conversation = JimUtil.getConversationList()
        that.loadmore = false
      }
    },
    pinConversation(item) { //置顶或取消置顶
      const options = {
        conversationID: item.conversationID,
        isPinned: !item.isPinned
      }
      let JIM = getApp().globalData.JIM;
      JIM.pinConversation(options).then(({
                                           data
                                         }) => {
        this.getConversation()
      }).catch(err => {})
    },
    deleteConversation(item) { //删除会话
      let that = this
      let JIM = getApp().globalData.JIM;
      uni.showModal({
        content: this.$t('list.index.gpvi89'),
        cancelText: this.$t('list.index.8gi6sv'),
        confirmColor: '#ff0000',
        success(res) {
          if (res.confirm) {

            	JimUtil.deleteConversation(item)
            	JIM.deleteConversationFromLocalAndSvr(item.conversationID).then(({
            		data
            	}) => {
            		that.getConversation()
            	}).catch(err => {})
          }
        }
      });
    },
    // ListTouch触摸开始
    ListTouchStart(e) {
      this.listTouchStart = e.touches[0].pageX
    },

    // ListTouch计算方向
    ListTouchMove(e) {
      this.listTouchDirection = e.touches[0].pageX - this.listTouchStart > 0 ? 'right' : 'left'
    },

    // ListTouch计算滚动
    ListTouchEnd(e) {
      if (this.listTouchDirection == 'left') {
        this.modalName = e.currentTarget.dataset.target
      } else {
        this.modalName = null
      }
      this.listTouchDirection = null
    }
  }
};
</script>
<style>

</style>
